﻿using Mapster;
using RsCms.Application.Settings.Dto;
using RsCms.Core;
using System.Text.Json;

namespace RsCms.Application.Settings
{
    public class SettingAppService: ISettingAppService
    {
        ISettingsDomainService settingsDomainService;
        public SettingAppService(ISettingsDomainService settingsDomainService)
        {
            this.settingsDomainService = settingsDomainService;
        }
        public async Task<List<Dto.SettingEditDto>> SaveAsync(List<Dto.SettingEditDto> settings)
        {
            var info= await settingsDomainService.SaveAsync(settings.Adapt<List<Entities.Settings>>());
            return info.Adapt<List<Dto.SettingEditDto>>();    
        }

        public async Task<List<Dto.SettingEditDto>>GetSettingListAsync(string group)
        {
            var info = await settingsDomainService.GetSettingListAsync(group);
            if(info!=null)
            {
                return info.Adapt<List<Dto.SettingEditDto>>();
            }
            return null;
        }
    
       public async Task<SiteInfoDto> GetSiteInfoAsync()
        {
            var settingsInfo = await settingsDomainService.GetSettingListAsync("site");
            SiteInfoDto siteInfo = new SiteInfoDto();
            siteInfo.Title = settingsInfo.FirstOrDefault(x => x.Key == "title")?.Value??"";
            siteInfo.Description = settingsInfo.FirstOrDefault(x => x.Key == "description")?.Value ?? "";
            siteInfo.MetaTitle = settingsInfo.FirstOrDefault(x => x.Key == "meta_title")?.Value ?? "";
            siteInfo.MetaDescription = settingsInfo.FirstOrDefault(x => x.Key == "og_title")?.Value ?? "";
            siteInfo.OgTitle = settingsInfo.FirstOrDefault(x => x.Key == "og_title")?.Value ?? "";
            siteInfo.OgDescription = settingsInfo.FirstOrDefault(x => x.Key == "og_description")?.Value ?? "";
            siteInfo.TwitterUrl = settingsInfo.FirstOrDefault(x => x.Key == "twitter_url")?.Value ?? "";
            siteInfo.TwitterTitle = settingsInfo.FirstOrDefault(x => x.Key == "twitter_title")?.Value ?? "";
            siteInfo.TwitterImage = settingsInfo.FirstOrDefault(x => x.Key == "twitter_image")?.Value ?? "";
            siteInfo.TwitterDescription = settingsInfo.FirstOrDefault(x => x.Key == "twitter_description")?.Value ?? "";

            return siteInfo;
        }

        public async Task DeleteAsync(string id)
        {
            await settingsDomainService.DeleteAsync(id);
        }
    }
}
